// pages/lock/lock.ts
// import { IAppOption } from "../../appoption"
//import { CarService } from "../../service/car"
//import { car } from "../../service/proto_gen/car/car_pb"
//import { rental } from "../../service/proto_gen/rental/rental_pb"
//import { TripService } from "../../service/trip"
import { TripService } from "../../service/trip"
import { routing } from "../../utils/routing"
// const shareLocationKey = "share_location"
Page({
  carID: '',
  data: {
    shareLocation: false,
    avatarURL: '',
    
  },

  onShareLocation(e: any){
    this.data.shareLocation = e.detail.value
      if (!this.data.shareLocation) {
          this.setData({
              avatarURL: '',
          })
      }
  },
  async onLoad(opt: Record<'car_id', string>) {
    const o: routing.LockOpts = opt
    this.carID = o.car_id
  },
  onGetUserInfo() {
    wx.getUserProfile({
      desc: '允许其他用户看到我此次行程头像',
      success: res => {
          this.setData({
              avatarURL: res.userInfo.avatarUrl,
              shareLocation: true,
          })
      },
      fail: console.log,
    })
  },
  onUnlockTap(){
    wx.getLocation({
      type:'gcj02',
      success:async loc=>{
        console.log(
          'starting a triping',{latitude:loc.latitude,longitude:loc.longitude}
        )
        if (!this.carID){
          console.error("carId is empty")
          return
        }
        const trip =await TripService.createTrip({
           carId:this.carID,
           start:{
             latitude:loc.latitude,
             longitude:loc.longitude,
           }
        })
        if(!trip.id){
          console.error("no trip Id in resoponse",trip)
          return
        }
        const tripID = trip.id
        wx.showLoading({
          title:'开锁中',
          mask:true,      
        })
        setTimeout(() => {
          wx.redirectTo({
            url: routing.drving({
              trip_id: tripID,
          }),
          complete: () => {
              wx.hideLoading()
          }
          })
        }, 2000)
      },
      fail:()=>{
        wx.showToast({
          icon:'none',
          title:'请前往设置页面授权位置信息',
        })
      }
    })

  },
})